import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import rjl.domain.User;

/**
 * Created by Administrator on 2017/3/3.
 */
public class TestHiberate {
    private Configuration configuration ;
    @Test
    public void configtest(){
        //创建configuration实例
        configuration = new Configuration();
        //自动加载配置文件
        configuration.configure("hibernate.cfg.xml");
        //构建sessionFactory实例
        SessionFactory sf = configuration.buildSessionFactory();
        /*session实例*/
        Session session = sf.openSession();
        Transaction transaction = session.beginTransaction();
        User user = new User();
        user.setUsername("30rjl");
        user.setPassword("0147852");
        session.save(user);
        transaction.commit();
        session.close();
    }
    /*查询一个id为3的数据对象*/
    @Test
    public void getTest(){
        configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory sf = configuration.buildSessionFactory();
        Session session = sf.openSession();
        Transaction transaction = session.beginTransaction();
        User user = null;
        user = (User) session.createQuery("from User a where a.password = ? and a.username = ?")
                .setParameter(0,"123456")
                .setParameter(1,"rjl")
                .uniqueResult();
        transaction.commit();
        session.close();
        System.out.println(user);
    }
    @Test
    public void Updatetest(){
        configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        User user = null;
        user = (User) session.createQuery("from User a where a.password = ? and a.username = ?")
                .setParameter(0,"123456")
                .setParameter(1,"rjl")
                .uniqueResult();
        user.setPassword("5823694");
        session.update(user);
        transaction.commit();
        session.close();
        System.out.println(user);
    }
    @Test
    public void Deleteste(){
        configuration = new Configuration();
        configuration.configure("hibernate.cfg.xml");
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        User user = null;
        user = (User) session.createQuery("from User a where a.password = ? and a.username = ?")
                .setParameter(0,"5823694")
                .setParameter(1,"rjl")
                .uniqueResult();
        session.delete(user);
        transaction.commit();
        session.close();
    }
}
